package io.renren.modules.store.controller;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.annotation.NoRepeatSubmit;
import io.renren.common.exception.RRException;
import io.renren.common.utils.BeanJudgeUtil;
import io.renren.common.utils.Query;
import io.renren.modules.reception.init.TableThemeCache;
import io.renren.modules.store.entity.TStoreRegionEntity;
import io.renren.modules.store.service.TStoreRegionService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.store.entity.TStoreDiningTableEntity;
import io.renren.modules.store.service.TStoreDiningTableService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author steakliu
 * @email 2319492349@qq.com
 * @date 2021-01-24 01:14:45
 */
@RestController
@RequestMapping("store/tstorediningtable")
public class TStoreDiningTableController extends AbstractController {
    @Autowired
    private TStoreDiningTableService tStoreDiningTableService;
    @Autowired
    private TStoreRegionService tStoreRegionService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("store:tstorediningtable:list")
    public R list(@RequestParam Map<String, Object> params){
        params.put("sellerId",getSeller());
        PageUtils page = tStoreDiningTableService.queryPage(params);
        return R.ok().put("page", page);
    }

    @RequestMapping("/stopOrStartDesk")
    @RequiresPermissions("store:tstorediningtable:stopOrStartDesk")
    public R stopOrStartDesk(@RequestParam Integer status , @RequestParam Long id, @RequestParam String style){
        tStoreDiningTableService.update(new UpdateWrapper<TStoreDiningTableEntity>()
            .eq("seller_id",getSeller())
                .eq("id",id)
                .set("status",status)
                .set("style",style)
        );
        return R.ok();
    }

    //锁定/解锁
    @RequestMapping("/lockDesk")
    //@RequiresPermissions("store:tstorediningtable:list")
    public R lockDesk(@RequestParam Long id,@RequestParam Integer status){
        tStoreDiningTableService.update(new UpdateWrapper<TStoreDiningTableEntity>()
            .set("status",status)
                .eq("seller_id",getSeller())
                .eq("id",id)
        );
        return R.ok();
    }


    /**
     * 前台展示数据（座位数列表和区域）
     */
    @RequestMapping("/listSeat")
    @RequiresPermissions("store:tstorediningtable:list")
    public R listSeat(@RequestParam Map<String, Object> params){
        params.put("sellerId",getSeller());
        //区域列表
        List<TStoreRegionEntity> regionList = tStoreRegionService.list(
                new QueryWrapper<TStoreRegionEntity>()
                        .eq("seller_id", getSeller())
                        .eq("store_type_id",params.get("storeTypeId"))
        );
        //座位列表
        Page<TStoreDiningTableEntity> dinningTableList = tStoreDiningTableService.queryTables(params);

        //座位集合
        List<Integer> seatNumList =  tStoreDiningTableService.getSeatNumList(params);

        //餐台格式

        Map<String,Object> hashMap = new HashMap<>();
        hashMap.put("regionList",regionList);
        hashMap.put("seatNumList",seatNumList);
        hashMap.put("dinningTableList",dinningTableList);
        hashMap.put("deskFormat", TableThemeCache.get(getSeller()));
        return R.ok().put("data", hashMap);
    }

    /**
     * 前台展示数据（座位数列表和区域）
     */
    @RequestMapping("/querySeatByStoreTypeId/{storeTypeId}/{page}/{limit}")
    @RequiresPermissions("store:tstorediningtable:list")
    public R querySeatByStoreTypeId(@PathVariable("storeTypeId") Long storeTypeId,
                                    @PathVariable("page") String page,
                                    @PathVariable("limit") String limit){
        //区域列表
        List<TStoreRegionEntity> regionList = tStoreRegionService.list(
                new QueryWrapper<TStoreRegionEntity>()
                        .eq("seller_id", getSeller())
                        .eq("store_type_id",storeTypeId)

        );
        //座位列表
        Map<String,Object> param = new HashMap<>();
        param.put("sellerId",getSeller());
        param.put("page",page);
        param.put("limit",limit);
        param.put("storeTypeId",storeTypeId);
        //座位列表
        Page<TStoreDiningTableEntity> dinningTableList = tStoreDiningTableService.queryTables(param);
        //座位集合
        Map<String,Object> params = new HashMap<>();
        params.put("sellerId",getSeller());
        params.put("storeTypeId",storeTypeId);
        List<Integer> seatNumList =  tStoreDiningTableService.getSeatNumList(params);

        Map<String,Object> hashMap = new HashMap<>();
        hashMap.put("regionList",regionList);
        hashMap.put("seatNumList",seatNumList);
        hashMap.put("dinningTableList",dinningTableList);
        return R.ok().put("data", hashMap);

    }


    /**
     * 前台展示数据（座位数列表和区域）
     */
    @RequestMapping("/querySeatById")
    @RequiresPermissions("store:tstorediningtable:list")
    public R querySeatById(@RequestParam("regionId") Long regionId,
                           @RequestParam("seatNum") Integer seatNum,
                           @RequestParam("status") Integer status,
                           @RequestParam("storeTypeId") Long storeTypeId,
                           @RequestParam("page") String page,
                           @RequestParam("limit") String limit){
        Map<String,Object> param = new HashMap<>();
        param.put("sellerId",getSeller());
        param.put("page",page);
        param.put("limit",limit);
        param.put("status",status);
        param.put("regionId",regionId);
        param.put("storeTypeId",storeTypeId);
        param.put("seatNum",seatNum);
        //座位列表
        Page<TStoreDiningTableEntity> dinningTableList = tStoreDiningTableService.queryTables(param);
        //区域列表
        List<TStoreRegionEntity> regionList = tStoreRegionService.list(
                new QueryWrapper<TStoreRegionEntity>()
                        .eq("seller_id", getSeller())
                        .eq("store_type_id",storeTypeId)

        );
        //座位集合
        Map<String,Object> params = new HashMap<>();
        params.put("sellerId",getSeller());
        params.put("storeTypeId",storeTypeId);
        List<Integer> seatNumList =  tStoreDiningTableService.getSeatNumList(params);

        Map<String,Object> hashMap = new HashMap<>();
        hashMap.put("dinningTableList",dinningTableList);
        hashMap.put("regionList",regionList);
        hashMap.put("seatNumList",seatNumList);
        return R.ok().put("data", hashMap);

    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("store:tstorediningtable:info")
    public R info(@PathVariable("id") Long id){
		TStoreDiningTableEntity tStoreDiningTable = tStoreDiningTableService.getById(id);

        return R.ok().put("tStoreDiningTable", tStoreDiningTable);
    }

    /**
     * 保存
     */
    @NoRepeatSubmit
    @RequestMapping("/save")
    @RequiresPermissions("store:tstorediningtable:save")
    public R save(@RequestBody TStoreDiningTableEntity tStoreDiningTable){
        TStoreDiningTableEntity one = tStoreDiningTableService.getOne(new QueryWrapper<TStoreDiningTableEntity>()
                .eq("store_type_id", tStoreDiningTable.getStoreTypeId())
                .eq("region_id", tStoreDiningTable.getRegionId())
                .eq("seller_id", getSeller())
                .eq("dining_table_no",tStoreDiningTable.getPrefix()+tStoreDiningTable.getNumber())
        );
        if (one != null){
            throw new RRException("该区域下已存在同名餐台,请重新输入");
        }
        if (BeanJudgeUtil.beanIsNull(tStoreDiningTable.getNumber())){
            tStoreDiningTable.setDiningTableNo(tStoreDiningTable.getPrefix());
        }else {
            tStoreDiningTable.setDiningTableNo(tStoreDiningTable.getPrefix()+tStoreDiningTable.getNumber());
        }
        tStoreDiningTable.setSellerId(getSeller());
        tStoreDiningTable.setStatus(1);
        tStoreDiningTable.setStyle(TableThemeCache.get(getSeller()).getFreeColor());
		tStoreDiningTableService.save(tStoreDiningTable);
        return R.ok();
    }

    /**
     * 批量保存
     */
    @RequestMapping("/saveBatch")
    @RequiresPermissions("store:tstorediningtable:save")
    @NoRepeatSubmit
    public R saveBatch(@RequestBody TStoreDiningTableEntity tableEntity){
        tableEntity.setSellerId(getSeller());
        tableEntity.setStyle(TableThemeCache.get(getSeller()).getFreeColor());
        List<TStoreDiningTableEntity> list = new ArrayList<>();
        TStoreDiningTableEntity storeDiningTableEntity = tStoreDiningTableService.getMaxNumberByPrefix(tableEntity);
        if (storeDiningTableEntity != null){
            for (int i = 1 ; i <= tableEntity.getDiningtableNum() ; i++){
                TStoreDiningTableEntity entity = new TStoreDiningTableEntity();
                tableEntity.setDiningTableNo(tableEntity.getPrefix()+(storeDiningTableEntity.getNumber()+i));
                tableEntity.setNumber(storeDiningTableEntity.getNumber()+i);
                BeanUtil.copyProperties(tableEntity,entity);
                list.add(entity);
            }
        }
        else {
            for (int i = 1 ; i <= tableEntity.getDiningtableNum() ; i++){
                TStoreDiningTableEntity entity = new TStoreDiningTableEntity();
                tableEntity.setDiningTableNo(tableEntity.getPrefix()+i);
                tableEntity.setNumber(i);
                BeanUtil.copyProperties(tableEntity,entity);
                list.add(entity);
            }
        }
        tStoreDiningTableService.saveBatch(list);
        return  R.ok();
    }
    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("store:tstorediningtable:update")
    public R update(@RequestBody TStoreDiningTableEntity tStoreDiningTable){
        TStoreDiningTableEntity one = tStoreDiningTableService.getOne(new QueryWrapper<TStoreDiningTableEntity>()
                .eq("seller_id", getSeller())
                .eq("store_type_id", tStoreDiningTable.getStoreTypeId())
                .eq("dining_table_no", tStoreDiningTable.getDiningTableNo())
                .notIn("id", tStoreDiningTable.getId())
        );
        if (!BeanJudgeUtil.beanIsNull(one)){
            throw new RRException("词区域下已存在同名餐台，请重新输入");
        }
        tStoreDiningTableService.updateById(tStoreDiningTable);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("store:tstorediningtable:delete")
    public R delete(@RequestBody Long[] ids){

		tStoreDiningTableService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
